package com.ikkong.api.intercept;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ikkong.api.TokenManager;
import com.ikkong.api.model.BaseResponse;
import com.ikkong.api.model.Code;
import com.ikkong.common.vo.User;
import com.ikkong.platform.model.Member;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;


/**
 * Token拦截器
 * 
 * @author malongbo
 * @date 15-1-18
 * @package com.pet.project.interceptor
 */
public class TokenInterceptor implements Interceptor {
	public void intercept(Invocation inv) {

		Controller controller = inv.getController();
		/*
		 * controller.getResponse().setHeader("Access-Control-Allow-Origin",
		 * "*");
		 * controller.getResponse().addHeader("Access-Control-Allow-Headers"
		 * ,"Origin, X-Requested-With, Content-Type, Accept");
		 */

		String token = controller.getPara("token");

		if (StringUtils.isEmpty(token)) {
			/*
			 * controller.renderJson(new BaseResponse(Code.ARGUMENT_ERROR,
			 * "签名不能为空")); return;
			 */
  
			BaseResponse ob=	new BaseResponse(Code.FAIL, "签名不能为空");
			String cb = controller.getPara("callback"); 
			String result = "";
			if (StringUtils.isEmpty(cb)) {
				result = JSONObject.toJSONString(ob);
			} else {
				result = cb + "(" + JSONObject.toJSONString(ob) + ")";
			}
			controller.renderText(result);
			return;
		}

		Member user = TokenManager.getMe().validate(token);
		if (user == null) {
			/*controller.renderJson(new BaseResponse(Code.TOKEN_INVALID, "签名失效"));
			return;*/
			
			BaseResponse ob=	new BaseResponse(Code.TOKEN_INVALID, "签名失效");
			String cb = controller.getPara("callback"); 
			String result = "";
			if (StringUtils.isEmpty(cb)) {
				result = JSONObject.toJSONString(ob);
			} else {
				result = cb + "(" + JSONObject.toJSONString(ob) + ")";
			}
			controller.renderText(result);
			return;
		}

		controller.setAttr("user", user);
		inv.invoke();
	}

}
